package com.itheima.reggie.impl;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import com.itheima.reggie.dto.SetmealDto;
import com.itheima.reggie.entity.Setmeal;

import com.itheima.reggie.entity.SetmealDish;
import com.itheima.reggie.mapper.SetmealMapper;

import com.itheima.reggie.service.SetmealDishService;
import com.itheima.reggie.service.SetmealService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.management.Query;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author chm
 * @version 1.0.0 v
 * @date 2022-08-13 21:31
 */
@Service
@Slf4j
public class SetmealServiceImpl extends ServiceImpl<SetmealMapper, Setmeal> implements SetmealService {

    @Autowired
    private SetmealDishService setmealDishService;





    @Override
    //保证套餐和菜品同时存在
    @Transactional
    public void saveWithDish(SetmealDto setmealDto) {
//保存套餐信息
        this.save(setmealDto);
        List<SetmealDish> setmealDishes = setmealDto.getSetmealDishes();
        setmealDishes.stream().map((item)->{
            item.setSetmealId(setmealDto.getId());
            return item;
        }).collect(Collectors.toList());
        //保存套餐与菜的关系

    setmealDishService.saveBatch(setmealDishes);


    }
    //查询套餐状态，确定是否可以删除
    //如果可以删除，则先删数据
    //删除关系中的数据

@Transactional
    public void removeWithDish(List<Long> ids) throws Exception {

        LambdaQueryWrapper<Setmeal>queryWrapper=new LambdaQueryWrapper<>();
        queryWrapper.in(Setmeal::getId,ids);
        queryWrapper.eq(Setmeal::getStatus,1);

        //判断是否处于售卖还是停售中
        int count = this.count(queryWrapper);
        if (count>0){
            throw new Exception("套餐正售卖，不可删除");
        }
        this.removeByIds(ids);

        LambdaQueryWrapper<SetmealDish>lambdaQueryWrapper=new LambdaQueryWrapper<>();

        lambdaQueryWrapper.in(SetmealDish::getSetmealId,ids);
        setmealDishService.remove(lambdaQueryWrapper);
}
}
